﻿using System.Linq;
using KL.UFrame.Core.Result;

namespace KL.UFrame.Api.Extension
{
    public static class ModelStateErrorExtension
    {
        /// <summary>
        /// usage: ModelState.GetErrors()
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetErrors(this System.Web.Http.ModelBinding.ModelStateDictionary model)
        {
            string errorString = string.Empty;
            if (!model.IsValid)
            {
                //获取所有错误的Key 
                var keys = model.Keys.ToList();
                //获取每一个key对应的ModelStateDictionary 
                errorString = keys.Select(key => model[key].Errors.ToList()).SelectMany(errors => errors).Aggregate(errorString, (current, error) => current + (error.ErrorMessage + ";"));
                if (errorString.StartsWith(";")) errorString = errorString.Remove(0, 1);
            }
            return errorString;
        }
        /// <summary>
        /// usage: ModelState.ToResultMessage()
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ResultMessage ToResultMessage(this System.Web.Http.ModelBinding.ModelStateDictionary model)
        {
            return new ResultMessage(-1, model.GetErrors());
        }
    }
}